package com.info.provider.web.think;

import com.info.provider.entity.Image;
import com.info.provider.entity.Think;
import com.info.provider.entity.ThirdSessionId;
import com.info.provider.service.ThinkService;
import com.info.provider.service.aliyun.oos.OSSUtils;
import com.info.provider.service.impl.SessionService;
import com.mars.app.base.CommResponse;
import com.mars.app.exception.ErrorCodeMsg;
import com.mars.app.exception.SystemException;
import com.mars.app.utils.DateUtil;
import com.mars.app.utils.MarsAssert;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * Created by pengshuo on 2018/2/1 14:27
 * Description: 微信小程序签到交互
 * Modified By:
 * Version:
 *
 * @author pengshuo
 */
@RestController
public class ThinkController {

    private Logger logger = LogManager.getLogger(this.getClass());

    @Autowired
    private SessionService sessionService;

    @Autowired
    private ThinkService thinkService;

    @Autowired
    private OSSUtils ossUtils;

    @Value("${aliyun.oss.ossKey}")
    private String ossKey;

    @Value("${aliyun.oss.accessUrl}")
    private String accessUrl;

    /**
     * thinkWhitImage
     * @param image image
     * @param think think
     * @param thirdSessionId thirdSessionId
     * @return
     */
    @PostMapping(value = {"thinkWhitImage"},produces = {"application/json; charset=UTF-8"})
    public CommResponse<Think> thinkWhitImage(MultipartFile file, Think think, Image image, ThirdSessionId thirdSessionId){
        try {
            // 缓存appId
            String appId = sessionService.appId(thirdSessionId.getThirdSessionId());
            // oss key
            String imageOSSKey = ossKey(appId,image.getType());
            image.setOssKey(imageOSSKey);
            // oss url
            image.setOssUrl(accessUrl + imageOSSKey);
            // image
            think.setImage(image);
            // appId
            think.setAppId(appId);
            // 存储在阿里云oss
            ossUtils.store(imageOSSKey,file.getInputStream());
            // 保存
            logger.debug("think {}",think);
            return new CommResponse(thinkService.create(think));
        }catch (Exception e){
            logger.error("thinkWhitImage Exception: {}",e);
            return new CommResponse<>(e);
        }
    }

    /**
     * thinkNoneImage
     * @param think think
     * @param thirdSessionId thirdSessionId
     * @return
     */
    @PostMapping(value = {"thinkNoneImage"},produces = {"application/json; charset=UTF-8"})
    public CommResponse<Think> thinkNoneImage(Think think,ThirdSessionId thirdSessionId){
        try {
            // 缓存appId
            String appId = sessionService.appId(thirdSessionId.getThirdSessionId());
            // appId
            think.setAppId(appId);
            // 保存
            logger.debug("think {}",think);
            return new CommResponse(thinkService.create(think));
        }catch (Exception e){
            logger.error("thinkNoneImage Exception: {}",e);
            return new CommResponse<>(e);
        }
    }

    /**
     * get Think by primary key
     * @param think Think
     * @return
     */
    @PostMapping(value = {"getThink"},produces = {"application/json; charset=UTF-8"})
    public CommResponse<Think> getThink(Think think,ThirdSessionId thirdSessionId){
        try {
            // check session
            sessionService.checkThirdSession(thirdSessionId.getThirdSessionId());
            // check uuid
            MarsAssert.check(StringUtils.isNotBlank(think.getUuid()),new SystemException(ErrorCodeMsg.ARGS_LOSE_ERROR));
            // return data
            return new CommResponse(thinkService.get(think.getUuid()));
        }catch (Exception e){
            logger.error("get Think Exception: {}",e);
            return new CommResponse<>(e);
        }
    }

    /**
     * 获取ossKey(example: wechat/20180413/xkjsj2jkfjs-20180413103512.jpeg)
     * @param appId
     * @return
     */
    private String ossKey(String appId,String fileType){
        return new StringBuilder(ossKey)
                .append("/")
                .append(DateUtil.yyyyMMdd())
                .append("/")
                // 用户 appId 截取，避免传递完整用户appId
                .append(appId.substring(4))
                .append("-")
                .append(DateUtil.yyyyMMddHHmmss())
                .append(".")
                .append(fileType)
                .toString();
    }

}
